package com.sansan.qiangji.handler;

import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.exception.UserAuthorizeException;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;

@Slf4j
@ControllerAdvice
public class GlobalException {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVO<Object> globalExceptionHandler(Exception e) {
        if (e instanceof UserAuthorizeException) {
            return ResultVOUtil.error(ResultEnum.UNIDENTIFIED);
        }
        if (e instanceof ServiceException) {
            ServiceException ex = (ServiceException) e;
            return ResultVOUtil.error(ex.getCode(), ex.getMessage());
        }
        if (e instanceof HttpMediaTypeNotSupportedException) {
            log.error("传参方式异常: {}", e.toString());
            return ResultVOUtil.error(ResultEnum.HTTP_TYPE_ERROR);
        }
        if (e instanceof HttpRequestMethodNotSupportedException) {
            log.error("请求方式异常: {}", e.toString());
            return ResultVOUtil.error(ResultEnum.HTTP_REQUEST_ERROR);
        }
        if (e instanceof HttpMessageNotReadableException) {
            log.error("JSON格式异常: {}", e.toString());
            return ResultVOUtil.error(ResultEnum.JSON_FORMAT_ERROR);
        }
        if (e instanceof MissingServletRequestParameterException) {
            log.error("参数类型异常: {}", e.toString());
            return ResultVOUtil.error(ResultEnum.PARAM_TYPE_ERROR);
        }
        log.error(e.getClass().getSimpleName());
        log.error(getTrace(e));
        return ResultVOUtil.error(ResultEnum.SYSTEM_ERROR);
    }

    public static String getTrace(Throwable t) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }
}
